//试卷
var paper = function(url, workarea, parms){
    var self = this;
    var questions = [];
    var answers = parms ? parms : {};
    var hide_submit = false;
    var favobj = new favTopic();
    self.url = url;
    self.typelist = null;
    self.answerBtn = null; 
    self.favBtn = null;
    self.canSubmit = false; //是否可以提交试卷
    self.canSwipe = false; //是否支持滑动手势
    self.current = 0;
    self.count = 0;
    //加载试卷
    this.load = function(){
        if(!self.url) return;
        self.init();
        $.mobile.showPageLoadingMsg('', '试题加载中...');
        $.get(self.url, function(data){
            answers['PAPERID'] = data['PAPERID'];
            if(data['TOPIC_TYPES'])
                self.showTypes(data['TOPIC_TYPES']);
            data = data['PAPER_QUESTIONS'];
            self.loadQuests(data);
        },'json')
        .error(function(){alert('试题加载出错')})
        .complete(function() { $.mobile.hidePageLoadingMsg(); })
    }
    //加载试题
    this.loadQuests = function(data){
        self.init();
        if(!data){
            $.mobile.showMessage('没有题目');
            return;
        }
        for(var id in data){
            var question_data = data[id]
            var qs = new question(self, question_data);
            questions.push(qs)
        }
        self.count = data.length;
        if(self.count > 0)
            self.show_question(0);
    }
    //从收藏中加载试题
    this.loadFav = function(){
        var data = favobj.favList();
        if(!data) return ;
        this.loadQuests(data);
    }
    //初始化试卷状态
    this.init = function(){
        answers['ANSWERS'] = [];
        questions = [];
        self.count = 0;
        self.current = 0;
    }
    
    //指定上一页按钮
    this.setPrevBtn = function(obj){
        obj.off('click');
        obj.click(function(){self.prev();})
    }
    //指定上一页按钮
    this.setNextBtn = function(obj){
        obj.off('click');
        obj.click(function(){self.next();})
    }
    //指定上一页按钮
    this.setResultBtn = function(obj){
        obj.off('click');
        obj.click(function(){self.showAnswer();})
    }
    //指定确定按钮
    this.setAnswerBtn = function(obj){
        obj.off('click');
        obj.click(function(){
            self.next();
        })
        self.answerBtn = obj;
    }
    //指定收藏按钮
    this.setFavBtn = function(obj){
        obj.off('click');
        obj.click(function(){
            var qs = questions[self.current];
            var quest = qs.toJson();
            favobj.toggleFav(quest)
            showFav(qs.id)
        })
        self.favBtn = obj;
    }
    //在按钮上标示出当前试题是否在收藏中
    var showFav = function(questid){
        if(!self.favBtn) return;
        if(favobj.isFav(questid)){
            self.favBtn.addClass('isfav')
        }else{
            self.favBtn.removeClass('isfav')
        }
    }
    
    //显示问题
    this.show_question = function(id){
        var qs = questions[id];
        showFav(qs.id);
        this.show_submit(qs.trunks);
        for(var tid in qs.trunks){
            var trunk = qs.trunks[tid];
            var no = id+1;
            var num = tid==0 ? '【'+no+'】' : '';
            var title = num+trunk.title;
            workarea.html(title+trunk.make_answer_sheet());
            workarea.trigger('create');
        }
        if(qs.type == '001' || qs.type == '004'){
            workarea.find('input:radio').change(function(){
                //不知道为什么，change事件会触发2次。所以用settimeout回避
                setTimeout(function(){self.next()}, 1);
            })
        }
    }
    
    //决定确定按钮是否显示
    this.show_submit = function(trunks){
        if(!hide_submit) return true;
        if(trunks.length > 1 && self.submit_btn != null){
            self.submit_btn.val('确定')
            self.submit_btn.show();
        }else if(trunks[0].type == '002' && self.submit_btn != null){
            self.submit_btn.val('多选确定')
            self.submit_btn.show();
        }else{
            self.submit_btn.hide();
        }
    }
    
    //下一题
    this.next = function(){
        this.save_answer();
        if(self.current == self.count-1){
            if(self.canSubmit)
                self.submit();
            else
                $.mobile.showMessage('已经是最后一题');
            return;
        }
        self.current = self.current+1
        this.show_question(self.current);
    }
    
    //上一题
    this.prev = function(){
        this.save_answer();
        if(self.current == 0){
            $.mobile.showMessage('已经是第一题');
            return false;
        }
        self.current = self.current-1
        this.show_question(self.current);
    }
    //保存当前题的答案
    this.save_answer = function(){
        var TOPIC_ID = questions[self.current].id;
        var TOPIC_TYPE_ID = questions[self.current].typeid;
        self.clearAnswer(TOPIC_ID);
        
        workarea.find('input').each(function(i, obj){
            var QUESTION_ID = $(obj).attr('name');
            var OPTION_ID = $(obj).val();
            if($(this).attr('checked')){
                var answer = {
                    'TOPIC_ID':TOPIC_ID,
                    'TOPIC_TYPE_ID':TOPIC_TYPE_ID,
                    'QUESTION_ID':QUESTION_ID,
                    'OPTION_ID':OPTION_ID
                }
                answers['ANSWERS'].push(answer);
            }
        })
    }
    //清除某一题的答案
    this.clearAnswer = function(topicid){
        if(!answers || !answers['ANSWERS']) return ;
        for(var i in answers['ANSWERS']){
            if(answers['ANSWERS'][i]['TOPIC_ID'] == topicid){
                answers['ANSWERS'].splice(i,1);
            }
        }
    }
    
    //显示出正确答案
    this.showAnswer = function(){
        workarea.find('label.correct').css('background-color','green');
        workarea.find('div.correctcontent').show()
    }
    
     //提交作业
    this.submit = function(){
        $.mobile.showPageLoadingMsg('', '正在提交作业...');
        $.ajax({
            url : 'data.php?a=TK_WORKANSWER',
            type : 'post',
            dataType : 'json',
            data : {answersJson:JSON.stringify(answers)},
            success : function(result){
                if(result['resultFlg'] != null && result['resultFlg']=='true'){
                    alert('您的最终得分：'+result['score']);
                }else{
                    $.moble.showMessage('提交作业出错')
                }
            }
        })
        .fail(function() { alert("失败"); })
        .always(function() { $.mobile.hidePageLoadingMsg(); });
    }
    
    //显示试题类型列表
    this.showTypes = function(options){
        if(!self.typelist) return false;
        var html = '';
        for(var i in options){
            html += "<option value='"+options[i]['Fulltopictypecd']+"'>"+options[i]['QUESTION_TYPE_NM']+"</option>";
        }
        self.typelist.html(html);
    }
    this.load();
    //左右滑动切题
    if(self.canSwipe) {
        $.mobile.activePage.bind('swipeleft', function(){
            self.next();
        })
        $.mobile.activePage.bind('swiperight', function(){
            self.prev();
        })
    }
}

//题目
var question = function(paper, data){
    var self = this;
    self.id = self.type = '';
    self.paper = paper;
    self.trunks = self.answers = [];
    
    this.init = function(data){
        self.id = data['TOPIC_ID'];
        self.type = data['TOPIC_TYPE_CD'];
        self.typeid = data['TOPIC_TYPE_ID'];
        
        var trunk_data = data['TOPIC_TRUNK'];
        for(var i in trunk_data){
            var tnk = new trunk(self, trunk_data[i])
            //如果题干中没有题型，则题干的题型与该题的题型一致
            if(tnk.type == null ){
                tnk.type = self.type;
            }
            self.trunks.push(tnk);
        }
    }
    //返回原始数据
    this.toJson = function(){
        return data;
    }
    this.init(data);
}

//题干
var trunk = function(question, data){
    var self = this;
    self.question = question;
    self.title, self.id, self.result = '';
    self.options = [];
    
    this.init = function(data){
        self.id = data['QUESTION_ID'];
        self.options = data['QUESTION_OPTIONS'];
        self.title = data['QUESTION_TITLE'];
    }
    
    //生成答题区域
    this.make_answer_sheet = function(){
        switch (self.type){
            
            case '001' :
                return self.make_options(self, 'radio')
                break;
            case '002' :
                return self.make_options(self, 'checkbox')
                break;
            case '004' :
                return self.make_just(self)
                break;
            case '005':
                var content = self.options[0]['OPTION_CONTENT'];
                return "<div class='correctcontent' style='display:none'>"+content+"</div>";
        }
        return '';
    }
    
    //生成选择项
    this.make_options = function(tnk, type){
        var options = tnk.options;
        var html = '<fieldset data-role="controlgroup" data-type="vertical">';
        for(var i in options){
            var cls  = this.isCorrect(options[i]) ? 'class="correct"' : '';
            html += '<label '+cls+'>'+options[i]['OPTION_CONTENT']+'<input name="'+tnk.id+'" value="'+options[i]['OPTION_ID']+'" type="'+type+'"></label>\n';
        }
        html += '</fieldset>';
        return html;
    }
    
    //生成判断项
    this.make_just = function(tnk){
        var option = tnk.options[0];
        var cls;
        var html = '<fieldset data-role="controlgroup" data-type="vertical">';
        cls  = this.isCorrect(option) ? 'class="correct"' : '';
        html += '<label '+cls+'>真<input name="'+tnk.id+'" value="1" type="radio"></label>\n';
        cls  = this.isCorrect(option) ? '' : 'class="correct"';
        html += '<label '+cls+'>假<input name="'+tnk.id+'" value="0" type="radio"></label>\n';
        html += '</fieldset>';
        return html;
    }
    //选项是否为正确选项
    this.isCorrect = function(option){
        return option['ISTRUE'] == '1' ? true : false;
    }
    this.init(data);
}

var favTopic = function(){
    var pre = 'fav_quest_'+student.getLoginName()+'_';
    //收藏与取消收藏
    this.toggleFav = function(quest){
        if(this.isFav(quest['TOPIC_ID'])){
            this.removeFav(quest['TOPIC_ID'])
        }else{
            this.addFav(quest);
        }
    }
    //添加到收藏
    this.addFav = function(quest){
        var key = pre+quest['TOPIC_ID'];
        return localStorage.setItem(key, JSON.stringify(quest))
    }
    //移除收藏
    this.removeFav = function(quesid){
        var key = pre+quesid;
        return localStorage.removeItem(key)
    }
    //判断是在收藏
    this.isFav = function(quesid){
        var key = pre+quesid;
        return localStorage.getItem(key) ? true : false;
    }
    //查看收藏列表
    this.favList = function(){
        var data = [];
        var prelen = pre.length;
        for(var i=0;i<localStorage.length;i++){
            var key = localStorage.key(i);
            if(key.substr(0, prelen) == pre){
                data.push(JSON.parse(localStorage.getItem(key)))
            }
        }
        return data;
    }
}